#include "ThreadPool.h"

NetWork::ThreadPool::ThreadPool(size_t threadCounts, size_t maxTask, bool waitAllTasksComplete) : 
    MaxTask(maxTask), bShutDown(false), bWaitAllTasksComplete(waitAllTasksComplete)
{
    for (size_t i = 0; i < threadCounts; i++) {
        Threads.push_back(std::thread([this](){
            while (true) {
                Task task;
                {
                    std::unique_lock<std::mutex> lock(Mutex);

                    //线程池处于 shutdown 状态, 同时 不等待任务结束 或者 队列为空时 退出循环
                    if ((bShutDown && !bWaitAllTasksComplete) ||
                        (bShutDown && Tasks.empty()))
                        break;

                    Consumer.wait(lock, [this](){
                        return !Tasks.empty() || bShutDown;
                    });

                    if (Tasks.empty())
                        continue;

                    task = Tasks.front();
                    Tasks.pop();

                    Productor.notify_one();
                }

                if (task)
                    task();
            }
        }));
    }
}

NetWork::ThreadPool::~ThreadPool()
{
    bShutDown = true;

    if (!bWaitAllTasksComplete)
    {
        std::unique_lock<std::mutex> lock(Mutex);
        std::queue<Task> empty;
        Tasks.swap(empty);

        //更新线程状态(shutdown)
        Productor.notify_all();
        Consumer.notify_all();

        for (auto& t : Threads)
            t.detach();

    }

    else {
        //更新线程状态(shutdown)
        Productor.notify_all();
        Consumer.notify_all();

        for (auto& t : Threads)
            t.join();
    }
}
